﻿/*苏兴迎 E-Mail:284238436@qq.com*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
namespace MVC
{

    public class IHttpServer
    {
        public static HttpListener Server=null;
        private static SessionClear sessionClear = new SessionClear();
        private static Interceptor interceptor_;
        public RouteMap Route;
        private static bool isStop = false;
        private bool issuccess = false;
        private string port;
        public IHttpServer(Interceptor interceptor = null)
        {
            SetConsoleCtrlHandler(cancelHandler, true);
            issuccess = true;

            //if (!Directory.Exists("WebRoot"))
            //{
            //    Directory.CreateDirectory("WebRoot");
            //}
            if (!Directory.Exists("Resources"))
            {
                Directory.CreateDirectory("Resources");
            }

            Config.AppExe = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            Config.RootPath = System.IO.Directory.GetCurrentDirectory();
            interceptor_ = interceptor;
            Route = new RouteMap();

            Route.Interceptor = interceptor_ != null;

            if (!Command.readMime())
            {
                Log.Print("Mime配置文件读取失败");
                issuccess = false;
            }
            if (!Command.readConifg())
            {
                Log.Print("Conifg配置文件读取失败");
                issuccess = false;
            }
        }

        public void Start(bool isForm = true)
        {
            if (issuccess)
            {
                try
                {
                    Command.isWinForm = isForm;
                    port = Command.configFile["Server"]["Port"].ToString();

                    // string maxThreads = Command.Command.configFile["Server"]["maxThreads"].ToString();
                    Server = new HttpListener();

                    Server.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                    Server.Prefixes.Add(String.Format("http://+:{0}/", port));
                    Server.Stop();
                    Server.Start();
                    Log.Print("Server Start Port:" + port);
                    Thread.Sleep(500);
                    if (!Command.isWinForm)
                        new Thread(RunCommand).Start();
                    Server.BeginGetContext(new AsyncCallback(MainProcess), Server);
                }
                catch (Exception e)
                {

                    Log.Print("服务启动[IHttpServer]:" + e.Message);
                   // throw e;
                }
            }
            else
            {
                Log.Print("服务启动失败");
            }
        }
        public string getPort()
        {
            return port.ToString();
        }
        private void RunCommand()
        {
            Console.WriteLine("\"clear\" Clear Page Cache");
            Console.WriteLine("\"show\" Show Page Cache");
            Console.WriteLine("\"quit\" Exit System");
            while (true)
            {
                String msg = Console.ReadLine();
                switch (msg)
                {
                    case "clear":
                        Command.clearPageCache();
                        break;
                    case "show":
                        Command.showPageCache();
                        break;
                    case "quit":
                        Stop();
                        System.Environment.Exit(0);
                        break;
                }

            }
        }
        private static void Stop()
        {
            isStop = true;
            sessionClear.Stop();
            Console.WriteLine("Stop......");
            Server.Stop();            
            Server.Close();
        }
        public void Close()
        {
            isStop = true;
            sessionClear.Stop();
            Console.WriteLine("Stop......");
            if (Server != null)
            {
                Server.Stop();
                Server.Close();
            }

        }
        private void MainProcess(IAsyncResult ar)
        {
            if (isStop) return;
            HttpListener socket = null;
            HttpListenerContext context = null;
            try
            {
                Server.BeginGetContext(new AsyncCallback(MainProcess), Server);
                socket = ar.AsyncState as HttpListener;
                context = socket.EndGetContext(ar);

            }
            catch (Exception e)
            {

                Log.Print("执行方法[MainProcess]:" + e.Message);
            }

            try
            {
                Command command = new Command();
                command.RunRoute(context, Route, interceptor_);

            }
            catch (Exception e)
            {

                Log.Print("执行方法[command.RunRoule]:" + e.Message);
            }

        }
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);

        public static bool HandlerRoutine(int CtrlType)
        {
            switch (CtrlType)
            {
                case 2:
                    //    Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭  
                    Stop();
                    break;
            }
            //   Console.ReadLine();
            return true;
        }
    }
}
